Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    isLogin: true // true为登录模式，false为注册模式
  },
  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },
  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },
  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value });
  },
  onLogin() {
    const { username, password } = this.data;
    if (!username || !password) {
      wx.showToast({ title: '请输入用户名和密码', icon: 'none' });
      return;
    }
    wx.request({
      url: 'http://localhost:3000/api/user/login',
      method: 'POST',
      data: { username, password },
      success(res) {
        if (res.data && res.data.code === 0) {
          // 保存用户信息到本地存储
          wx.setStorageSync('userInfo', res.data.user);
          
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            success() {
              // 返回上一页或首页
              wx.navigateBack({
                fail() {
                  wx.switchTab({
                    url: '/pages/user/goods/index'
                  });
                }
              });
            }
          });
        } else {
          wx.showToast({ title: res.data.message || '登录失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  onRegister() {
    const { username, password, confirmPassword } = this.data;
    
    if (!username || !password || !confirmPassword) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    
    if (password !== confirmPassword) {
      wx.showToast({ title: '两次密码不一致', icon: 'none' });
      return;
    }
    
    wx.request({
      url: 'http://localhost:3000/api/user/register',
      method: 'POST',
      data: { username, password },
      success(res) {
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: '注册成功',
            icon: 'success',
            success() {
              // 注册成功后切换到登录模式
              this.setData({
                isLogin: true,
                password: '',
                confirmPassword: ''
              });
            }
          });
        } else {
          wx.showToast({ title: res.data.message || '注册失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  switchMode() {
    this.setData({
      isLogin: !this.data.isLogin,
      username: '',
      password: '',
      confirmPassword: ''
    });
  },
  goAdminLogin() {
    wx.navigateTo({
      url: '/pages/admin/login/index'
    });
  }
}); 